package controller.login;

import pojo.account.Manager;
import pojo.account.Reader;
import service.AccountService;
import service.LoginService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginController", value = "/LoginController")
public class LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String id = request.getParameter("id");
        String password = request.getParameter("password");
        String identity = request.getParameter("identity");

        String path = null;

        if (new LoginService().login(id, password, identity)) {
            AccountService accountService = new AccountService();
            if (identity.equals("reader")) {
                Reader reader = accountService.getReader(id);
                path = "/ReaderIndexController";
                session.setAttribute("reader", reader);
            } else if (identity.equals("manager")) {
                Manager manager = accountService.getManager(id);
                path = "/ManagerIndexController";
                session.setAttribute("manager", manager);
            }

            request.getRequestDispatcher(path).forward(request, response);
            return;
        }

        request.setAttribute("errorMessage", "账号或密码错误");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}
